﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using EnvDTE;

namespace CodeGeneration.Artech
{
    public abstract class Generator
    {
        protected abstract IDictionary<string, Template> CreateTemplates();

        protected abstract Template CreateTemplate();
        public void Run()
        {
            RunCore();
            RemoveUnusedFiles();
        }
        protected virtual void RunCore()
        {
            var directory = Path.GetDirectoryName(TransformContext.Current.Host.TemplateFile);
            foreach (var item in CreateTemplates())
            {
                item.Value.EnsureInitialized();
                item.Value.RenderToFile(item.Key);
            }

            var template = CreateTemplate();
            if (null == template) return;
            template.EnsureInitialized();
            template.Render();
        }
        protected virtual void RemoveUnusedFiles()
        {
            List<string> files = new List<string>();
            string directory = Path.GetDirectoryName(TransformContext.Current.Host.TemplateFile);
            foreach (var item in CreateTemplates())
            {
                if (directory != null) files.Add(Path.Combine(directory, item.Key));
                item.Value.EnsureInitialized();
                item.Value.RenderToFile(item.Key);
            }
            var projectItems = TransformContext.Current.TemplageProjectItem.ProjectItems.Cast<ProjectItem>().ToArray();
            foreach (ProjectItem projectItem in projectItems)
            {
                string fileName = projectItem.FileNames[0];
                if (!files.Contains(fileName))
                {
                    projectItem.Delete();
                }
            }
        }
    }
}